package authen;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import realm.CustomerRealm;

/**
 * 测试自定义Realm认证
 *
 * @author lwh
 */
public class TestCustomerRealmAuthenticator {

    private static Logger logger = LoggerFactory.getLogger(TestCustomerRealmAuthenticator.class);

    public static void main(String[] args) {

        // 创建默认安全管理器
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        // 设置自定义Realm
        CustomerRealm realm = new CustomerRealm();
        securityManager.setRealm(realm);
        // 使用默认安全管理器
        SecurityUtils.setSecurityManager(securityManager);
        // 获取用户主体
        Subject subject = SecurityUtils.getSubject();
        // 创建用户凭证信息
        UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "123");
        // 用户认证
        try {
            subject.login(token);
            logger.info("用户认证状态：" + subject.isAuthenticated());
        } catch (UnknownAccountException e) {
            logger.info("用户信息错误");
        } catch (IncorrectCredentialsException e) {
            logger.info("凭证信息错误");
        }

    }

}
